#include "sht3x_utils.h"

#define POLYNOMIAL                  (0x131) // P(x) = x^8 + x^5 + x^4 + 1 = 1 0011 0001

// 计算CRC校验和
uint8_t sht3xUtilsCalcCrc(uint8_t *data, uint8_t len)
{
    uint8_t bit; // bit mask
    uint8_t crc = 0xFF; // calculated checksum
    uint8_t byteCtr; // byte counter

    // 计算 8bit CRC 校验和
    for(byteCtr = 0; byteCtr < len; ++byteCtr)
    {
        crc ^= data[byteCtr];
        for(bit = 0; bit < 8; ++bit)
        {
            if(crc & 0x80) crc = (crc << 1) ^ POLYNOMIAL;
            else crc = (crc << 1);
        }
    }
    return crc;
}

// 验证CRC是否校验通过
int32_t sht3xUtilsVerifyCrc(uint8_t *data, uint8_t len, uint8_t checksum)
{
    uint8_t crc; // 计算出来的校验和
    crc = sht3xUtilsCalcCrc(data, len);// 计算8bit的CRC值

    // 检查crc值是否匹配
    // if(crc != checksum) return -1;// 不匹配
    // return 0;

    // CRC 值匹配 返回0 不匹配 返回-1
    return (crc == checksum) ? (0) : (-1);
}

// calculate temperature [°C]
float sht3xUtilsCalcTemperature(uint16_t rawValue)
{
    // T = -45 + 175 * rawValue / (2^16-1)
    return 175.0f * (float)rawValue / 65535.0f - 45.0f;
}

// calculate relative humidity [%RH]
float sht3xUtilsCalcHumidity(uint16_t rawValue)
{
    // RH = rawValue / (2^16-1) * 100
    return 100.0f * (float)rawValue / 65535.0f;
}

// calculate raw temperature [ticks]
uint16_t sht3xUtilsCalcRawTemperature(float temperature)
{
    // rawT = (temperature + 45) / 175 * (2^16-1)
    return (temperature + 45.0f) / 175.0f * 65535.0f;
}

// calculate raw relative humidity [ticks]
uint16_t sht3xUtilsCalcRawHumidity(float humidity)
{
    // rawRH = humidity / 100 * (2^16-1)
    return humidity / 100.0f * 65535.0f;
}
